﻿//==================================================================
// Copyright (C) 2015 福流网络
// 作 者：江怀玉
// 日 期：2015-04-22
// 描 述：数据列表页面基类
//        
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人       修改内容
// 1.00   2015/4/22     江怀玉           
//==================================================================

using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZX.DBModule;
using ZX.EHR.Library;
using ZX.BLL.Extend;

namespace ZX.Web.UI.Controls
{
    public class miniListPage : BasePage
    {
        /// <summary>
        /// 获取数据数据条件
        /// </summary>
        public string Condition
        {
            get
            {
                return GetStringFromQueryString("condition", "");
            }
        }







        /// <summary>
        /// 定义数据字段
        /// </summary>
        public string DataFields
        {
            get
            {
                return CreateDataGridColumns();
            }
        }

        /// <summary>
        /// 定义数据列
        /// </summary>
        public string DataColums
        {
            get
            {
                return GetColums();
            }
        }


        protected override void OnLoad(System.EventArgs e)
        {
            t_set_datagrid template = new  t_set_datagrid();
            BaseBussnies bll = new BaseBussnies(template);

            list =  bll.GetEntitys<t_set_datagrid>("function_id='"+FunctionID+"'");
         
            if (list == null)
            {
                list = bll.GetEntitys<t_set_datagrid>("entity='" + EntityName + "'");
            }


            // 权限 
            //if (this.UserId == null)
            //{
            //    Response.Redirect("/System/Error.aspx?message=1&functionId="+FunctionID);
            //}
            //if (!CheckFunctionRight())
            //{
            //    Response.Redirect("/System/Error.aspx?message=2&functionId="+FunctionID);
            //}


            var __list = bll.GetEntitys<t_set_entity>("table_name='" + this.EntityName + "'");
            t_set_entity entity = __list != null ? __list.FirstOrDefault() : null;
            if (entity != null)
            {
                _width = entity.edit_page_width;
                _height = entity.edit_page_height;
                EditPage = entity.edit_page;
                _list_self_script = entity.list_self_script;
                _edit_self_script = entity.edit_self_script;
            }
            // bll.GetEntitys
            // SetButtons();
            base.OnLoad(e);
        }
        private string _edit_self_script;
        public string Edit_self_script
        {
            get
            {
                return _edit_self_script;
            }
            set
            {
                _edit_self_script = value;
            }
        }
        private string _list_self_script;
        public string List_self_script
        {
            get
            {
                return _list_self_script;
            }
            set
            {
                _list_self_script = value;
            }
        }

        public string QueryHtml
        {
            get { return GeneratorQueryItem(); }
        }

        public virtual string GeneratorQueryItem()
        {
            if( list == null)
            {
                _bll.GetEntitys<t_set_datagrid>("function_id='" + FunctionID + "'");
            }
            StringBuilder strHTML = new StringBuilder("");
            string strDiv1 = "<div class=\"col1\" id=\"query_item_{0}\"><table class=\"query_table\"><tr><td class=\"label\">{1}</td><td class=\"exp\">{2}</td><td>{3}</td></tr></table></div>";
            string strDiv2 = "<div class=\"col2\" id=\"query_item_{0}\"><table class=\"query_table\"><tr><td class=\"label\">{1}</td><td class=\"exp\">{2}</td><td>{3}</td><td>{4}</td></tr></table></div>";

            var _list = list.OrderBy(p => p.sort);
            foreach (t_set_datagrid entity in _list)
            {
                if (entity.is_define_query == "N")
                {
                    continue;
                }
                if (entity.is_visiable == "N")
                {
                    continue;
                }
                if (entity.data_type.ToLower().Contains("date"))
                {
                    strHTML.AppendLine(string.Format(strDiv2, entity.name, entity.caption, GetExp(entity), CovertCtrl(entity), CovertCtrl(entity, 0)));
                }else if (entity.data_type.ToLower().Contains("int"))
                {
                    if (entity.is_between == "Y")
                    {
                        strHTML.AppendLine(string.Format(strDiv2, entity.name, entity.caption, GetExp(entity), CovertCtrl(entity), CovertCtrl(entity, 0)));
                    }
                    else
                    {
                        strHTML.AppendLine(string.Format(strDiv1, entity.name, entity.caption, GetExp(entity), CovertCtrl(entity)));
                    }
                }
                else
                {
                    strHTML.AppendLine(string.Format(strDiv1, entity.name, entity.caption, GetExp(entity), CovertCtrl(entity)));
                }
            }
            return strHTML.ToString();
        }

        public virtual string GetExp(t_set_datagrid entity)
        {
            string str = "";
            if (entity.data_type.Contains("char"))
            {
                str = "<select><option value=\"like\">包含</option><option value=\"=\">等于</option><option value=\" not like\">不包含</option> <option value=\"<>\">不等于</option> </select>";

            }
            else {
                str = "<select><option value=\"=\">等于</option><option value=\">\">大于</option><option value=\"<\">小于</option><option value=\"between\">在..之间</option></select>";
            }
            return str;
        }


        public virtual string CovertCtrl(t_set_datagrid entity,int index =1)
        {
            if (index == 1)
            {
                if (entity.data_type.ToLower() == "uniqueidentifier")
                {
                    if (entity.column_type == "combobox")
                    {
                        return string.Format("<input name=\"{0}\" class=\"mini-combobox\" style=\"width:100%;\" data=\"{0}_data\" />", entity.name);
                    }
                    if (entity.column_type == "treeselect")
                    {
                        return string.Format("<input name=\"{0}\" class=\"mini-combobox\" style=\"width:100%;\" data=\"{0}_data\" />", entity.name);
                    }
                }
                if (entity.data_type.ToLower().Contains("int"))
                {
                    if (entity.column_type == "checkboxcolumn")
                    {
                        return string.Format("<input name=\"{0}\" class=\"mini-checkbox\" style=\"width:100%;\" data=\"{0}_data\" />", entity.name);
                    }
                    else
                    {
                        return string.Format("<input name=\"{0}\" class=\"mini-textbox\" style=\"width:100%;\" data=\"{0}_data\" />", entity.name);
                    }
                }
                if (entity.data_type.ToLower().Contains("date"))
                {
                    return string.Format("<input name=\"{0}\" class=\"mini-datepicker\" style=\"width:100%;\" data=\"{0}_data\" />", entity.name);
                }
            }
            else
            {
                if (entity.data_type.ToLower() == "uniqueidentifier")
                {
                    if (entity.column_type == "combobox")
                    {
                        return string.Format("<input name=\"{0}_1\" class=\"mini-combobox\" style=\"width:100%;\" data=\"{0}_data\" />", entity.name);
                    }
                    if (entity.column_type == "treeselect")
                    {
                        return string.Format("<input name=\"{0}_1\" class=\"mini-combobox\" style=\"width:100%;\" data=\"{0}_data\" />", entity.name);
                    }
                }
                if (entity.data_type.ToLower().Contains("int"))
                {
                    if (entity.column_type == "checkbox")
                    {
                        return string.Format("<input name=\"{0}_1\" class=\"mini-checkbox\" style=\"width:100%;\" data=\"{0}_data\" />", entity.name);
                    }
                    else
                    {
                        return string.Format("<input name=\"{0}_1\" class=\"mini-textbox\" style=\"width:100%;\" data=\"{0}_data\" />", entity.name);
                    }
                }
                if (entity.data_type.ToLower().Contains("date"))
                {
                    return string.Format("<input name=\"{0}_1\" class=\"mini-datepicker\" style=\"width:100%;\" data=\"{0}_data\" />", entity.name);
                }
            }

            //默认
            return string.Format("<input name=\"{0}\" class=\"mini-textbox\" style=\"width:100%;\" data=\"{0}_data\" />",entity.name);
        }

     
        public int _width;
        /// <summary>
        ///编辑页面宽
        /// </summary>
        public int EditWindowWidth
        {
            get
            {
                if (_width < 600)
                {
                    return 600;
                }
                return _width;
            }
            set
            {
                if (_width != value && value > 600)
                {
                    _width = value;
                }
            }
        }

        public bool AllowEdit
        {
            get
            {
                return GetStringFromQueryString("allowedit", "flase") == "true";
            }
        }



        public int _height;
        /// <summary>
        ///编辑页面高
        /// </summary>
        public int EditWindowHeight
        {
            get
            {
                if (_height < 450)
                {
                    return 450;
                }
                return _height;
            }
            set
            {
                if (_height != value && value > 450)
                {
                    _height = value;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string EditPage
        {
            get;
            set;
        }

        /// <summary>
        /// 定义样式
        /// </summary>
        public string DataTableCss
        {
            get
            {
                return GetColumsCss();
            }
        }

        public string QuciklyQueryFields
        {
            get
            {
                return GetDataQueryFields();
            }
        }

        public string DataQueryFields
        {
            get
            {
                return GetDataQueryFields();
            }
        }

        /// <summary>
        /// 获取用来快速搜索的字段
        /// </summary>
        /// <returns></returns>
        public virtual string GetDataQueryFields()
        {
            if (list == null)
            {
                t_set_datagrid template = new t_set_datagrid();
                BaseBussnies<t_set_datagrid> bll = new BaseBussnies<t_set_datagrid>(template);
                list = bll.GetEntityListByCondition<t_set_datagrid>(" entity='" + EntityName + "'");
            }
            if (list == null)
            {
                return "";
            }
            var _list = list.Where(p => p.is_query == "Y");
            string _field= "";
            foreach (var item in _list)
            {
                _field = _field + item.name+",";
            }

            return _field==string.Empty?"":_field.Remove(_field.Length-1,1);
        }

       public IList<t_set_datagrid> list;
     
        /// <summary>
        /// 生成数据列头和数据对象
        /// </summary>
        /// <returns></returns>
        public virtual string CreateDataGridColumns()
        {
            if (list == null)
            {
                t_set_datagrid template = new t_set_datagrid();
                BaseBussnies<t_set_datagrid> bll = new BaseBussnies<t_set_datagrid>(template);
                list = bll.GetEntityListByCondition<t_set_datagrid>(" entity='" + EntityName + "' and is_visiable<>'N'");
            }
            string _strHtml = "key:'{0}',label:'{1}',width:{2},{3}";
            if (list == null)
            {
                return ("{" + string.Format(_strHtml, "Not Data", "Not Data", 400, "formatter:\"\"") + "},");
            }
            StringBuilder _sbHtml = new StringBuilder("");
            var _list = list.Where(p => p.is_visiable == "Y").OrderBy(p => p.sort).ToList();
            int i = 0;
            string _header = "";
            foreach (t_set_datagrid _template in _list)
            {
                i = i + 1;
                if (_header != _template.header)
                {
                    if (string.IsNullOrEmpty(_template.header))
                    {
                        var _tlist = _list.Where(p => p.header == _header);
                        _sbHtml.Append(string.Format("<div header=\"{0}\"><div property=\"columns\">", _header));
                        foreach (t_set_datagrid _t in _tlist)
                        {
                            if (string.IsNullOrEmpty(_t.column_type))
                            {
                                if (AllowEdit)
                                {
                                    _sbHtml.Append(string.Format("<div field=\"{0}\" width=\"{1}\" headerAlign=\"center\" allowSort=\"true\" renderer=\"{5}\">{2}<input property=\"editor\" class=\"mini-{4}\" style=\"width:100%;\" {3} /></div>\n",
                                        _t.name,
                                        _t.width,
                                        _t.caption,
                                        (!string.IsNullOrEmpty(_t.data_source_type) && !string.IsNullOrEmpty(_t.data_source) ? string.Format(" data=\"{0}_data\"", _t.name) : ""),
                                        string.IsNullOrEmpty(_t.editor) ? "textbox" : _t.editor, _t.data_formatter)
                                      );
                                }
                                else
                                {
                                    _sbHtml.Append(string.Format("<div field=\"{0}\" width=\"{1}\" headerAlign=\"center\" allowSort=\"true\"  renderer=\"{3}\" >{2}</div>\n", _t.name, _t.width, _t.caption, _t.data_formatter));
                                }
                            }
                            else
                            {
                                _sbHtml.Append(string.Format("<div field=\"{0}\" width=\"{1}\" headerAlign=\"center\" allowSort=\"true\" type=\"{3}\"  renderer=\"{5}\" >{2}<input property=\"editor\" class=\"mini-{4}\" style=\"width:100%;\" data=\"{0}_data\" /></div>\n", _t.name, _t.width, _t.caption, _t.column_type, string.IsNullOrEmpty(_t.editor) ? _t.column_type.Replace("column", "") : _t.editor, _t.data_formatter));
                            }
                        }
                        _sbHtml.Append("</div></div>");
                    }
                    _header = _template.header;
                }
                //不相等，但不为空
                if (_header == _template.header & !string.IsNullOrEmpty(_header))
                {
                    continue;
                }
                if (string.IsNullOrEmpty(_template.column_type))
                {
                    if (AllowEdit)
                    {
                        _sbHtml.Append(string.Format("<div field=\"{0}\" width=\"{1}\" headerAlign=\"center\" allowSort=\"true\">{2}<input property=\"editor\" class=\"mini-{4}\" style=\"width:100%;\" {3} /></div>\n",
                            _template.name,
                            _template.width,
                            _template.caption,
                            (!string.IsNullOrEmpty(_template.data_source_type) && !string.IsNullOrEmpty(_template.data_source) ? string.Format(" data=\"{0}_data\"", _template.name) : ""),
                            string.IsNullOrEmpty(_template.editor) ? "textbox" : _template.editor));

                    }
                    else
                    {
                        _sbHtml.Append(string.Format("<div field=\"{0}\" width=\"{1}\"  headerAlign=\"center\" allowSort=\"true\">{2}</div>\n", _template.name, _template.width, _template.caption));
                    }

                }
                else
                {
                    _sbHtml.Append(string.Format("<div field=\"{0}\" width=\"{1}\" headerAlign=\"center\" allowSort=\"true\" type=\"{3}\">{2} <input property=\"editor\" class=\"mini-{4}\" style=\"width:100%;\" data=\"{0}_data\" /></div>\n", _template.name, _template.width, _template.caption, _template.column_type, _template.column_type.Replace("column", "")));

                }
            }
            _sbHtml.Remove(_sbHtml.Length - 1, 1);
            return (_sbHtml.ToString());
        }

        public string ColumnDataSource
        {
            get
            {
                return GetColumnDataSource();
            }
        }

        /// <summary>
        /// 获取数据列控件字段
        /// </summary>
        /// <returns></returns>
        public virtual string GetColumnDataSource()
        {
            if (list == null)
            {
                return "";
            }
            var _dataList = list.Where(p =>!string.IsNullOrEmpty(p.data_source_type) && !string.IsNullOrEmpty(p.data_source));
            if (_dataList != null && _dataList.Count() > 0)
            {
                StringBuilder _jsDataSource = new StringBuilder("");
                foreach (t_set_datagrid datagrid in _dataList)
                {
                    
                    string _strFormat = "var {0}={1};";
                    string _oJson = "";
                    switch (datagrid.data_source_type.ToLower())
                    {
                        case "sql":
                           System.Data.DataTable dt =  this._bll.GetDataBySqlComm(datagrid.data_source);
                            _oJson = ZX.Common.Globals.DataTableToJSON(dt);
                            break;
                        case "json":
                            _oJson = datagrid.data_source;
                            break;
                        case "dic":
                            System.Data.DataTable dt1 = this._bll.GetDataBySqlComm(@"select id,value as [text] from v_data_base_dictionary_detail
where code='"+datagrid.data_source+"'");
                            _oJson = ZX.Common.Globals.DataTableToJSON(dt1);
                            break;
                        case "fix":
                            break;
                        default:
                            break;
                    }
                    if (_oJson == "")
                    {
                        continue;
                    }
                    else
                    {
                        _jsDataSource.AppendLine(string.Format(_strFormat, datagrid.name + "_data", _oJson));
                    }
                }
              return _jsDataSource.ToString();
            } return "";
        }


        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        public virtual string GetDetailDataFields()
        {
            if (list == null)
            {
                t_set_datagrid template = new t_set_datagrid();
                BaseBussnies bll = new BaseBussnies(template);
                //自定义列      
                {
                    list = bll.GetEntitys<t_set_datagrid>("EntityName='" + EntityName + "'");
                }
            }

            string _strHtml = "key:'{0}',label:'{1}',width:{2},{3}";
            if (list == null)
            {
                return ("{" + string.Format(_strHtml, "Not Data", "Not Data", 400) + "},");
            }
            StringBuilder _sbHtml = new StringBuilder("");
            var _list = list.Where(p => p.is_visiable == "Y").OrderBy(p => p.sort).ToList();
            int i = 0;
            foreach (t_set_datagrid _template in _list)
            {
                i = i + 1;
                {
                    _sbHtml.Append("{" + string.Format(_strHtml, _template.name, _template.caption,
                     (_template.width > 0 ? _template.width : 200)
                     , string.IsNullOrEmpty(_template.data_formatter) ? "sortable:true,resizeable:true,editor: new YAHOO.widget.TextareaCellEditor()" : "formatter:" + (_template.data_formatter + ",sortable:true,resizeable:true,editor: new YAHOO.widget.TextareaCellEditor()")) + "},");
                }
                if (i == 1)
                {
                    _sbHtml.Append("{" + string.Format(_strHtml, "iSun_Selected", "", 10, "formatter:\"checkbox\"") + "},");
                }


            }
            _sbHtml.Remove(_sbHtml.Length - 1, 1);
            return (_sbHtml.ToString());
        }

        /// <summary>
        /// 获得表头
        /// </summary>
        /// <returns></returns>
        public virtual string GetColums()
        {
            if (list == null)
            {
                t_set_datagrid template = new t_set_datagrid();
             
                BaseBussnies bll = new BaseBussnies(template);
                //自定义列
                {
                    list = bll.GetEntitys<t_set_datagrid>("name='" + EntityName + "'");
                }
                //list = bll.GetEntityListByCondition<DataListTemplate>("EntityName='" + EntityName + "'");
            }


            if (list == null)
            {
                return "";
            }
          
            StringBuilder _sbHtml = new StringBuilder("");
            var _list = list.OrderBy(p => p.sort);
            int i = 0;
            foreach (t_set_datagrid _template in _list)
            {
                _sbHtml.Append("'" + _template.name + "',");
                if (i == 0)
                {
                    _sbHtml.Append("'iSun_Selected',");
                    i = 1;
                }
            }
            _sbHtml.Remove(_sbHtml.Length - 1, 1);
            return (_sbHtml.ToString());
        }

        /// <summary>
        /// 页面标题
        /// </summary>
        public string PageTitle
        {
            get
            {
                return "";
            }
        }

        /// <summary>
        /// 获得表头
        /// </summary>
        /// <returns></returns>
        public virtual string GetColumsCss()
        {
            if (list == null)
            {
                t_set_datagrid template = new t_set_datagrid();
                BaseBussnies bll = new BaseBussnies(template);
                //自定义列
                {
                    list = bll.GetEntitys<t_set_datagrid>("EntityName='" + EntityName + "'");
                }

            }
            string _strHtml = ".yui-skin-sam .yui-dt-col-{0}$width:{1}@\n";
            if (list == null)
            {
                return (string.Format(_strHtml, "Not Data", 400)).Replace("$", "{").Replace("@", "}");
            }
            StringBuilder _sbHtml = new StringBuilder("");
            var _list = list.OrderBy(p => p.sort);
            int i = 0;
            foreach (t_set_datagrid _template in _list)
            {
                i = i + 1;
                if (i == _list.Count())
                {
                    _sbHtml.Append(_strHtml.Replace("{0}", _template.name).Replace("{1}", "100%"));
                }
                else
                {
                    _sbHtml.Append(_strHtml.Replace("{0}", _template.name).Replace("{1}", _template.width < 200 ? "200px" : _template.width.ToString() + "px"));
                }
            }
            _sbHtml.Remove(_sbHtml.Length - 1, 1);
            return (_sbHtml.ToString());
        }

        /// <summary>
        /// 按钮组
        /// </summary>
        public string BtnItems
        {
            get;
            set;
        }

        public string Left_BtnItems
        {
            get;
            set;
        }

        public string BtnItems_Group1
        {
            get;
            set;
        }

        public string BtnItems_Group2
        {
            get;
            set;
        }

        public string BtnItems_Group3
        {
            get;
            set;
        }

        public string BtnItems_Group4
        {
            get;
            set;
        }
        /// <summary>
        /// 按钮事件
        /// </summary>
        public string BtnEvents
        {
            get;
            set;
        }

        /// <summary>
        /// 初始化按钮事件
        /// </summary>
        public string InitBtnEvents
        {
            get;
            set;
        }



        ///// <summary>
        ///// 页面标题
        ///// </summary>
        //public string PageTitle
        //{
        //    get
        //    {
        //        SysFunction entity = (new BaseBussnies(new SysFunction())).GetEntityByCondition<SysFunction>("functionid = '"+this.FunctionID+"'");
        //        if (entity == null)
        //        {
        //            return "";
        //        }
        //        this.Page.Title = entity.Name;
        //        return entity.Name;
        //    }
        //}


         //<summary>
         //设置按钮操作权限
         //</summary>
        public virtual void SetButtons()
        {
 
        }


        /// <summary>
        /// 设置默认查询
        /// </summary>
        public string DefineCondition
        {
            get
            {
                BaseBussnies bll = new BaseBussnies();
                IList<QuerySolution> list = bll.GetEntitys<QuerySolution>("add_user='"+this.UserId+"' and FunctionID='" + this.FunctionID + "' and IsDefault='Y'");
                if (list != null)
                {
                    QuerySolution entity = list.FirstOrDefault();
                    return entity == null ? "" : entity.Condition;
                }
                return "";
            }
        }


        public IList<OpertionItems> opertionItems = new List<OpertionItems>();


        public string getItem(string area)
        {
            var _items = opertionItems.Where(p => p.area == area).ToList();
            StringBuilder strHTML = new StringBuilder("");
            if (_items == null)
            {
                return "";
            }
            foreach (var _item in _items)
            {
                strHTML.Append(_item.item);
            }
            return strHTML.ToString();
        }
    }

    public class OpertionItems
    {
        public string area
        {
            get;
            set;
        }

        public string item
        {
            get;
            set;
        }
    }
    
}
